package dept

import (
	"context"
	"fast-boot/app/model"
	"github.com/jinzhu/copier"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 部门分页列表
func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListLogic) List(req *types.SysDeptListReq) (resp []*types.SysDeptItem, err error) {
	deptModel := model.SysDeptModel{}
	var items []*model.SysDeptModel
	l.svcCtx.GormClient.GormDb.Model(deptModel).
		Scopes(
			deptModel.WithStatus(req.Status),
			deptModel.WithKeywords(req.Keywords)).
		Order("sort asc, id asc ").
		Scan(&items)
	return DeptListTree(items, 0), nil
}

// DeptListTree 转化树结构
func DeptListTree(list []*model.SysDeptModel, parentID int64) []*types.SysDeptItem {
	res := make([]*types.SysDeptItem, 0)
	for _, item := range list {
		if item.ParentID == parentID {
			var dept types.SysDeptItem
			_ = copier.Copy(&dept, item)
			dept.Children = DeptListTree(list, item.Id)
			res = append(res, &dept)
		}
	}
	return res
}
